package com.my.study.quartz;

import com.my.study.annotation.JobHandler;
import com.my.study.annotation.JobMethodHandler;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author: yidujun
 * @create: 2021/04/27 18:28
 */
@Slf4j
@Component
public class JobInitial implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(JobHandler.class);
        Set<Map.Entry<String, Object>> entries = beans.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> map = iterator.next();
            Class<?> aClass = map.getValue().getClass();
            JobHandler classJob = aClass.getAnnotation(JobHandler.class);
            if (classJob == null) {
                continue;
            }
            String className = classJob.name();
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                JobMethodHandler methodJob = method.getAnnotation(JobMethodHandler.class);
                if (methodJob != null) {
                    try {
                        String methodName = methodJob.name();
                        String methodCron = methodJob.cron();
                        String start = methodJob.start();
                        String jobId = className + "_" + methodName;
                        QuartzManager.createScheduleJob(scheduler, aClass, jobId, methodCron);
                        if ("0".equals(start)) {
                            QuartzManager.pauseJob(scheduler, jobId);
                        }
                    } catch (Exception e) {
                        log.error("job 初始化失败", e);
                    }

                }
            }
        }
    }
}
